package com.example.aiquestions.service.impl;

import com.example.aiquestions.entity.GraphData;
import com.example.aiquestions.mapper.GraphMapper;
import com.example.aiquestions.mapper.SubjectMapper;
import com.example.aiquestions.service.GraphService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class GraphServiceImpl implements GraphService {

    @Autowired
    private GraphMapper graphMapper;
    
    @Autowired
    private SubjectMapper subjectMapper;

    @Override
    public List<GraphData> getAllGraphData() {
        return graphMapper.selectAllGraphData();
    }

    @Override
    public GraphData getGraphDataById(Long id) {
        return graphMapper.selectGraphDataById(id);
    }

    @Override
    public List<GraphData> getGraphDataBySubjectId(Long subjectId) {
        return graphMapper.selectGraphDataBySubjectId(subjectId);
    }

    @Override
    @Transactional
    public Long addGraphData(GraphData graphData) {
        // 设置科目名称
        if (graphData.getSubjectId() != null && graphData.getSubjectName() == null) {
            String subjectName = subjectMapper.getSubjectById(graphData.getSubjectId()).getName();
            graphData.setSubjectName(subjectName);
        }
        
        graphMapper.insertGraphData(graphData);
        return graphData.getId();
    }

    @Override
    @Transactional
    public int batchAddGraphData(List<GraphData> graphDataList) {
        if (graphDataList == null || graphDataList.isEmpty()) {
            return 0;
        }
        
        // 为每个数据设置科目名称
        for (GraphData graphData : graphDataList) {
            if (graphData.getSubjectId() != null && graphData.getSubjectName() == null) {
                String subjectName = subjectMapper.getSubjectById(graphData.getSubjectId()).getName();
                graphData.setSubjectName(subjectName);
            }
        }
        
        return graphMapper.batchInsertGraphData(graphDataList);
    }

    @Override
    @Transactional
    public boolean updateGraphData(GraphData graphData) {
        // 设置科目名称
        if (graphData.getSubjectId() != null && graphData.getSubjectName() == null) {
            String subjectName = subjectMapper.getSubjectById(graphData.getSubjectId()).getName();
            graphData.setSubjectName(subjectName);
        }
        
        return graphMapper.updateGraphData(graphData) > 0;
    }

    @Override
    @Transactional
    public boolean deleteGraphData(Long id) {
        return graphMapper.deleteGraphDataById(id) > 0;
    }

    @Override
    @Transactional
    public int deleteGraphDataBySubjectId(Long subjectId) {
        return graphMapper.deleteGraphDataBySubjectId(subjectId);
    }
}
